package com.cnsoft.manager.h5.home;

import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.cnsoft.framework.beans.common.RESTResultBean;
import org.cnsoft.framework.beans.user.UserBean;
import org.cnsoft.framework.token.TokenServiceImpl;
import org.cnsoft.framework.utils.EmptyHelper;
import org.cnsoft.framework.weixin.MyWeixinCommonSupport;
import org.cnsoft.framework.weixin.bean.WxCallBackParamBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * 菜单入口（用户授权） 菜单分类
 * 
 * @author Zmsoft
 * @version 0.1.0 2018/4/2
 * @since 0.1.0 2018/4/2
 */
@Controller
@RequestMapping(value = "/manager/1.0/h5/home")
public class WXManagerController extends MyWeixinCommonSupport {
	
	/**
	 * 打开菜单
	 * 
	 * @param [menuId]
	 * @return ModelAndView
	 * @throws Exception
	 * @author Zmsoft
	 * @version 0.1.0 2018/4/2
	 * @since 0.1.0 2018/4/2
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public ModelAndView doWXSaasIndex(@PathVariable String menuId) throws Exception {
		logger.debug("doWXSaasIndex==>>>" + menuId);
		ModelAndView model = new ModelAndView("/weixin/WXIndex");
		// 回调地址
		model.addObject("redirect", URLEncoder.encode(getSystemConfigService().getWxServerUrl() + "/WXSaas/Back/" + menuId, SYSTEM_CHARSET));
		// 目标地址
		model.addObject("login_href", "/WXIndex/Login/" + menuId);
		model.addObject("appid", getWxShareConfigService().getWxAppID());
		model.addObject("state", 2);
		model.addObject("menuId", menuId);
		logger.debug("doWXSaasIndex==>>>" + model);
		return model;
	}

	/**
	 * 微信授权回调地址-微信菜单地址
	 * 
	 * @param [request,
	 *            response, menuId, wxUserBean]
	 * @return ModelAndView
	 * @throws Exception
	 * @author Zmsoft
	 * @version 0.1.0 2018/4/2
	 * @since 0.1.0 2018/4/2
	 */
	@RequestMapping(value = "/WXSaas/Back/{menuId}", method = RequestMethod.GET)
	public ModelAndView doWXBack(HttpServletRequest request, HttpServletResponse response, @PathVariable String menuId, WxCallBackParamBean wxCallBackParamBean) throws Exception {
		ModelAndView model = new ModelAndView("/weixin/WXerror");
		logger.debug("doWXBack==>>>" + menuId);
		logger.debug("====doWXBack=====doWXBack====code>>>>>>>>>>>" + wxCallBackParamBean.getCode());
		if (EmptyHelper.isEmpty(wxCallBackParamBean.getCode()))
			model.addObject("msg", "授权失败！");
		else {
			// 第二步：通过code换取网页授权access_token
			wxCallBackParamBean.setAppid(getWxShareConfigService().getWxAppID());
			wxCallBackParamBean.setSecret(getWxShareConfigService().getWxAppSecret());
			Map<String, String> wxmsg = myWeixinCommonSupport.loadAccessToken(wxCallBackParamBean);
			String openId = wxmsg.get("openid");
			if (EmptyHelper.isNotEmpty(openId)) {
				logger.info("====doWXBack====doWXBack=====openId>>>>>>>>>>>" + openId);
				wxCallBackParamBean.setOpenid(openId);
				wxCallBackParamBean.setAccess_token(wxmsg.get("access_token"));

				// 开始自动登录
				return doWXLogin(request, response, menuId, wxCallBackParamBean);
			} else {
				model.addObject("msg", "授权失败！");
			}
		}
		return model;
	}

	/**
	 * 微信用户登陆<br>
	 * 0首页1文章2问卷3商品4广告5活动
	 * @param [request, response, menuId, wxUserBean]
	 * @return ModelAndView
	 * @throws Exception
	 * @author Zmsoft
	 * @version 0.1.0 2018/4/2
	 * @since 0.1.0 2018/4/2
	 */
	@RequestMapping(value = "/WXSaas/login/{menuId}", method = RequestMethod.GET)
	public ModelAndView doWXLogin(HttpServletRequest request, HttpServletResponse response, @PathVariable String menuId, WxCallBackParamBean wxCallBackParamBean) throws Exception {
		logger.debug("doWXMenuMain==>>>menuId=>>>" + menuId);
		logger.debug("doWXMenuMain==>>>" + wxCallBackParamBean);
		// 开始自动登录
		RESTResultBean<UserBean> result = getPlayerLoginService().doWeixinLogin(request, response, wxCallBackParamBean);

		TokenServiceImpl tokenService = TokenServiceImpl.build(request, (UserBean)result.getData());
		tokenService.setCacheService(myCacheService);
		tokenService.prepareClientTimestamp();
		tokenService.setWaitTimeSecond(1800);
		tokenService.saveToken(request);// 处理TOKEN
		
		ModelAndView model = new ModelAndView("/weixin/WXSaasMenu");
		
		model.addObject("token", tokenService.getToken());
		
		model.addObject("data", wxCallBackParamBean);
		
		model.addObject("menuId", menuId);

		model.addObject("apiServerUrl", getSystemConfigService().getApiServerUrl());
		model.addObject("pcServerUrl", getSystemConfigService().getPcServerUrl());
		model.addObject("wxServerUrl", getSystemConfigService().getWxServerUrl());

		return model;
	}

}
